<template>
  <div>
    <div>
      <h2 style="text-align: center">发布新课程</h2>
    </div>
    <!-- 发布新课程 -->
    <el-steps
      :active="active"
      align-center
      process-status="wait"
      style="margin-bottom: 30px"
    >
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>
    <!-- 填写课程基本信息 -->
    <el-form
      ref="courseForm"
      :model="course"
      :rules="rules"
      label-width="120px"
    >
      <!-- 课程标题 -->
      <el-form-item label="课程标题" prop="title">
        <el-input
          v-model="course.title"
          placeholder="示例:机器学习项目课:从基础到搭建项目视频课程。专业名称注意大小写"
        />
      </el-form-item>

      <!-- 课程类别 -->
      <el-form-item label="课程类别" prop="subjectId">
        <!-- 一级分类 -->
        <el-select
          v-model="course.subjectParentId"
          placeholder="请选择"
          @change="subjectParentChange"
        >
          <el-option
            v-for="item in subjectNestedList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <!-- 课程二级分类 -->
        <el-select placeholder="请选择" v-model="course.subjectId">
          <el-option
            v-for="item in subjectTwoList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师" prop="teacherId">
        <el-select placeholder="请选择讲师" v-model="course.teacherId">
          <el-option
            v-for="item in teacherSearchList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 总课时 -->
      <el-form-item label="总课时" prop="lessonNum">
        <el-input-number
          v-model="course.lessonNum"
          controls-position="right"
          :min="1"
        ></el-input-number>
      </el-form-item>

      <!-- 课程简介 -->
      <el-form-item label="课程简介" prop="description">
        <Tinymce v-model="course.description"></Tinymce>
      </el-form-item>

      <!-- 课程封面 -->
      <el-form-item label="课程封面">
        <el-upload
          class="upload-demo"
          ref="upload"
          :show-file-list="false"
          :action="`${BASE_URL}/file/upload?host=cover`"
          :limit="1"
          :before-upload="beforeCoverUpload"
          :on-success="coverUploadSuccess"
        >
          <img :src="course.cover" />
        </el-upload>
      </el-form-item>

      <!-- 课程价格 -->
      <el-form-item label="课程价格" prop="price">
        <el-input-number
          v-model="course.price"
          controls-position="right"
          :min="0"
        ></el-input-number>
        元
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
  <script>
import courseApi from "@/api/course";
import subjectApi from "@/api/subject";
import teacherApi from "@/api/teacher";
import Tinymce from "@/components/Tinymce";
export default {
  data() {
    return {
      BASE_URL: process.env.BASE_API, // 获取dev配置文件中的api地址
      active: 1,
      course: {
        title: "", // 标题
        subjectId: "", // 课程二级分类id
        subjectParentId: "", // 课程一级分类id
        lessonNum: 0, // 总课时
        cover: "https://hopu-dome.oss-cn-hangzhou.aliyuncs.com/default2.jpg", // 课程封面
        teacherId: "", //讲师id
        price: 0, // 课程价格
        description: "", // 课程简介
      },
      subjectNestedList: [], // 一级课程分类
      teacherSearchList: [], // 讲师分类
      subjectTwoList: [], // 二级课程分类
      //   格式校验
      rules: {
        title: [
          { required: true, message: "请输入课程标题", trigger: "blur" },
          { max: 50, message: "长度最大为 50 个字符", trigger: "blur" },
        ],
        lessonNum: [
          { type: "number", message: "总课时必须是数字", trigger: "blur" },
          { required: true, message: "请输入总课时", trigger: "blur" },
        ],
        subjectId: [
          { required: true, message: "请选择课程分类", trigger: "change" },
        ],
        teacherId: [
          { required: true, message: "请选择课程讲师", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
      },
    };
  },
  components: {
    Tinymce,
  },
  created() {
    //
    this.init();
  },
  methods: {
    // 初始化一级课程列表分类
    initSubjectList() {
      subjectApi.getList().then((res) => {
        this.subjectNestedList = res.data;
      });
    },
    // 所有讲师列表
    getTeacherAll() {
      teacherApi.getTeacherAll().then((res) => {
        this.teacherSearchList = res.data;
      });
    },
    // 课程类别一级分类改变时触发
    subjectParentChange(val) {
      // 根据当前一级分类信息，查看二级分类
      // console.log(val);
      // 找到一级分类下的children
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id == val) {
          this.subjectTwoList = this.subjectNestedList[i].children;
          // 清空查询条件中的二级分类id、
          this.course.subjectId = "";
        }
      }
    },

    // 课程封面上传校验
    beforeCoverUpload(file) {
      // 判断上传图片格式
      if (file.type !== "image/jpeg") {
        this.$message.error("上传图片格式只能是JPG格式!");
        return false;
      }
      // 判断上传图片大小
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error("上传图片不能超过2MB!");
        return false;
      }
    },
    // 封面上传成功之后的回调
    coverUploadSuccess(response, file, fileList) {
      // 根据成功的地址，为背景图赋值
      this.course.cover = response.data.ossUrl;
    },
    // 初始化当前页面
    init() {
      // 根据路由判断当前是添加还是修改
      if (this.$route.params && this.$route.params.id) {
        // 根据课程d获取当前要更新的课程信息
        // 绑定到页面中
        const courseId = this.$route.params.id;
        // console.log(courseId);
        this.getCourseById(courseId);

        // 获取讲师下拉框数据
        this.getTeacherAll();

        // 获取一级课程分类数据
        this.initSubjectList();
      } else {
        // 添加操作
        // 获取一级课程分类数据
        this.initSubjectList();

        // 调用获取所有讲师方法
        this.getTeacherAll();
      }
    },
    next() {
      // 进行数据格式的合法校验
      this.$refs["courseForm"].validate((valid) => {
        if (valid) {
          // 验证通过
          // 判断执行的是什么操作
          if (this.course.id) {
            // 调用更新讲师的方法
            this.updateCourse()
          } else {
            // console.log("添加");
            // 调用添加讲师的方法
            this.addCourse();
          }
        } else {
          //   失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 执行添加课程基本信息
    addCourse() {
      // 调用添加课程api
      courseApi.addCourse(this.course).then((res) => {
        // 提示添加成功信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        // 添加成功后，跳转至添加课程大纲列表页面，通过编程式路由
        this.$router.push({ path: `/course/chapter/${res.data}`});
        // console.log(res);
      });
    },
    //
    updateCourse(){
      // 调用更新课程信息的api
      courseApi.updateCourse(this.course).then(res=>{
        // 更新成功
        this.$message({
          type: "success",
          message: "更新成功!",
        });
        // 添加成功后，跳转至编辑大纲页面，通过编程式路由对象形式
        this.$router.push({ name: "CourseChapter",params:{id:this.course.id} });
      }).catch(err=>{
        this.$message({
          type: "error",
          message: "更新失败!",
        });
      })
    } 
    ,
    // 根据id获取课程基本信息
    getCourseById(id) {
      // 调用根据id获取课程基本信息的api
      courseApi.getCourseById(id).then((res) => {
        this.course = res.data;

        subjectApi.getList().then((res) => {
          // 根据当前一级分类信息，查看二级分类
        const parentSubject = this.subjectNestedList.find(
          (item) => item.id == this.course.subjectParentId
        );
        if (parentSubject) {
          // 找到一级分类下的children
          this.subjectTwoList = parentSubject.children;
        }
        });
        
      });
    },
  },
};
</script>